package com.uetoken.cn.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.base.MyApplication;
import com.uetoken.cn.bean.AdvertisingBean;
import com.uetoken.cn.bean.AppConfig;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.LocationBean;
import com.uetoken.cn.bean.SignBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.AppUpdate;
import com.uetoken.cn.utils.GetCurrentLocation;
import com.uetoken.cn.utils.GlideApp;
import com.uetoken.cn.view.DialogHelper;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * @date 2018年7月24日09:25:41
 */
public class SplashActivity extends AppCompatActivity implements WebResponse {
    /**
     * 获取配置信息的网络请求码
     */
    private static final int NETWORK_REQUEST_CONFIG = 10;
    /**
     * 签到时的网络请求码
     */
    private static final int NETWORK_REQUEST_SIGN = 20;
    @BindView(R.id.iv_activity_splash_advertising)
    ImageView mIvAdvertising;
    @BindView(R.id.tv_activity_splash_second)
    TextView mTvSecond;
    @BindView(R.id.layout_bottom_logo)
    ImageView mBottomLogo;


    /**
     * 是否第一次启动app
     */
    private boolean isFirstOpenApp;
    /**
     * 广告倒计时
     */
    private int TIME = 3;

    private String longtitude = "0";
    private String latitude = "0";
    /**
     * 第三方app启动且程序不在后台
     */
    private boolean fromThirdAppLauncher = false;
    private boolean isLogin = false;//是否登录状态
    private boolean isSign = false;//是否可以开始签到
    private boolean isLocation = false;//是否获取到定位位置
    private boolean isClientID = false;//第一次启动APP判断是否获取到个推ID
    private boolean isGetConfig = false;
    private int signResult;//签到值成功
    private SignBean signBean;
    private Uri uri;
    private boolean isAdIsOn;
    private String adUrl;
    private QMUITipDialog qmuiTipDialog;
    private Dialog mDialog;
    private String privacyprotocol;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }
        QMUIStatusBarHelper.translucent(this);
        setContentView(getLayoutId());
        initView();
        initData();
    }

    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    public void initView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    public void initData() {
        Intent intent = getIntent();
        uri = intent.getData();
        if (uri != null) {
            isLocation = true;
            isClientID = true;
        }
        //默认为正式模式
        boolean mode = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getBoolean(Constant.SP_MODE_CHANGE, false);
        Constant.isTestMode = mode;
        isFirstOpenApp = SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).getBoolean(Constant.SP_APP_IS_FIRST_OPEN, true);
        isLogin = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getBoolean(Constant.SP_WHETHER_LOGIN, false);
        if (isFirstOpenApp) {
            //提供一个等待获取个推id的转圈
            showLoading();
            //设置一个Handler变量用于接收返回的个推ClientID
            MyApplication.getInstance().setHandler(mHandler);
        } else {
            isClientID = true;
            beginSign("initData");
        }
        //开始定位
        String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};
        //开始定位
        AndPermission.with(this).runtime().permission(mPermissionList).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                GetCurrentLocation.getLocationCity();
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                isLocation = true;
                beginSign("AndPermission");
//                ToastUtils.showShort(getResources().getString(R.string.str_permission_refuse_causing_an_exception));
            }
        }).start();

        mHandler.sendEmptyMessageDelayed(3, 6000);
    }

    private void showPrivacyDialog() {
        if (mDialog == null) {
            mDialog = DialogHelper.showPrivacyDialog(SplashActivity.this, getString(R.string.str_warm_prompt), generateSp(getString(R.string.str_privacy_policy))
                    , getString(R.string.str_disagree_backout), getString(R.string.str_agree), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            AppUtils.exitApp();
                            isFirstOpenApp = true;
                            SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).put(Constant.SP_APP_IS_FIRST_OPEN, isFirstOpenApp);
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            isFirstOpenApp = false;
                            SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).put(Constant.SP_APP_IS_FIRST_OPEN, isFirstOpenApp);
                            if (isGetConfig) {
                                doSomething();
                            }
                        }
                    });
        }
        mDialog.show();
    }

    private SpannableString generateSp(String text) {
        final String highlight = getString(R.string.str_privacy_policy_agreement);
        SpannableString sp = new SpannableString(text);
        int start = 0, end;
        int index;
        while ((index = text.indexOf(highlight, start)) > -1) {
            end = index + highlight.length();
            sp.setSpan(new QMUITouchableSpan(ContextCompat.getColor(SplashActivity.this, R.color.color_app_theme), ContextCompat.getColor(SplashActivity.this, R.color.color_app_theme),
                    ContextCompat.getColor(SplashActivity.this, R.color.durban_White), ContextCompat.getColor(SplashActivity.this, R.color.durban_White)) {
                @Override
                public void onSpanClick(View widget) {
                    if (!ObjectUtils.isEmpty(privacyprotocol)) {
                        privacyprotocol = new String(EncodeUtils.base64Decode(privacyprotocol));
                        toWebActivity(privacyprotocol);
                    }
                }
            }, index, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            start = end;
        }
        return sp;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    LogUtils.dTag("SplashActivity==", "SplashActivity== handleMessage  1");
                    if (isFirstOpenApp) {
                        dissmissDialog();
                        String getuiClient = (String) msg.obj;
                        //第一次启动保存个推clientID
                        SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).put(Constant.SP_GE_TUI_TOKEN, getuiClient);
//                        isFirstOpenApp = false;
//                        //获取个推id后将第一次启动的值变为false
//                        SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).put(Constant.SP_APP_IS_FIRST_OPEN, isFirstOpenApp);
                        isClientID = true;
                        if (!isGetConfig) {
                            getConfig();
                        }
                        //获取到个推ID后开始正式的业务逻辑
                    }
                    break;
                case 2:
                    LogUtils.dTag("SplashActivity==", "SplashActivity== handleMessage  2");
                    mTvSecond.setVisibility(View.VISIBLE);
                    mTvSecond.setText(getResources().getString(R.string.str_jump) + TIME + "s");
                    TIME--;
                    if (TIME >= 0) {
                        mHandler.sendEmptyMessageDelayed(2, 1000);
                    } else {
                        toMainActivity();
                    }
                    break;
                case 3:
                    isClientID = true;
                    isLocation = true;
                    beginSign("handleMessage3");
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 正式开始业务逻辑
     */
    private void doSomething() {
        /**
         * 获取第三方app数据
         */
        if (!isFirstOpenApp) {
            //有数据说明是第三方app拉起的
            if (uri != null) {
                fromThirdApp(uri);
            } else {
                //没有数据说明不是第三方app拉起的
                checkAppUpdate();
            }
        }
    }


    /**
     * 从第三方app跳转过来的
     *
     * @param uri
     */
    private void fromThirdApp(Uri uri) {
        //从哪个app跳转过来的(优谷或pcn)
        String merchant = uri.getHost();
        String actionType = uri.getQueryParameter("actionType");
        int type = Integer.parseInt(actionType);
        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_ACTION_TYPE, type);
        //第三方app传递过来的数据
        String json = uri.getQueryParameter("json");
        LogUtils.dTag("SplashActivity==", "SplashActivity== fromThirdApp  uri = " + uri.toString() + " isLogin = " + isLogin);

        //主界面在栈中,说明程序在后台,
        if (type == 2000 || type == 8000) {
            SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_MERCHANT, merchant);
            SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_JSON_DATA, json);
            //2000为调起ue支付时自定义的值
            if (isLogin) {
                //登录状态直接跳转到支付界面
                startActivity(new Intent(SplashActivity.this, PayToMerchantsActivity.class));
                finish();
            } else {
                //未登录状态直接跳转到登录界面
                Intent loginIntent = new Intent(this, LoginActivity.class);
                loginIntent.putExtra("flag", "pay");
                startActivity(loginIntent);
                finish();
            }
        } else if (type == 5000 || type == 5001 || type == 4000) {
            boolean isBind = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getBoolean(Constant.THRID_APP_BIND, false);
            //pcn、优谷4000授权后
            String nodeCode = uri.getQueryParameter("nodeCode");
            if (isLogin) {
                if (ActivityUtils.isActivityExistsInStack(MainActivity.class) && isBind) {
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_BIND, false);
                    Intent bindIntent = new Intent(this, BindAccountSettingActivity.class);
                    bindIntent.putExtra("nodeCode", nodeCode);
                    startActivity(bindIntent);
                } else {
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                }
                finish();
            } else {
                Intent loginIntent = new Intent(this, LoginActivity.class);
                loginIntent.putExtra("nodeCode", nodeCode);
                loginIntent.putExtra("flag", "login");
                startActivity(loginIntent);
                finish();
            }
        } else if (type == 4001) {
            //4001为pcn授权ue按返回键后的自定义的值
            if (isLogin) {
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.THRID_APP_BIND, false);
                Intent bindIntent = new Intent(this, BindAccountSettingActivity.class);
                bindIntent.putExtra("nodeID", "");
                startActivity(bindIntent);
                finish();
            } else {
                Intent loginIntent = new Intent(this, LoginActivity.class);
                loginIntent.putExtra("nodeID", "");
                loginIntent.putExtra("flag", "login");
                startActivity(loginIntent);
                finish();
            }
        } else if (type == 6000 || type == 6001 || type == 7000) {
            String nodeCode = uri.getQueryParameter("nodeCode");
            SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.SP_TRIRDPARTY_APP_REQUEST_AUTHORIZATION, uri.toString());
            //优谷请求授权
            if (isLogin) {
                Intent intentToAuth = new Intent(this, APPAuthorizationActivity.class);
                intentToAuth.putExtra("uriHost", merchant);
                intentToAuth.putExtra("actionType", actionType + "");
                intentToAuth.putExtra("nodeCode", nodeCode + "");
                startActivity(intentToAuth);
                finish();
            } else {
                Intent intentToLogin = new Intent(this, LoginActivity.class);
                intentToLogin.putExtra("isAuthorization", true);
                intentToLogin.putExtra("uriHost", merchant);
                intentToLogin.putExtra("flag", "authorization");
                intentToLogin.putExtra("nodeCode", nodeCode + "");
                intentToLogin.putExtra("actionType", actionType + "");
                startActivity(intentToLogin);
                finish();
            }
        } else {
            toMainActivity();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLocation(LocationBean locatinEvent) {
        longtitude = locatinEvent.getLogitude();
        latitude = locatinEvent.getLatitude();
        isLocation = true;
        beginSign("getLocation");
    }

    /**
     * 开始签到
     */
    private void beginSign(String model) {
        LogUtils.dTag("SplashActivity==", "SplashActivity== beginSign model = " + model + " isClientID = " + isClientID + " isLocation = " + isLocation);
        isSign = isClientID && isLocation;
        if (isLogin) {
            if (isSign) {
                isClientID = false;
                isLocation = false;
                OkHttpUtils.getInstance().getStringWithParam(SplashActivity.this, ApiHelper.getUserSignUrl(), NETWORK_REQUEST_SIGN,
                        Params.getUserSignParams(longtitude, latitude));
            }
        } else {
            if (!isGetConfig) {
                getConfig();
            }
        }
    }

    /**
     * 获取配置信息
     */
    private void getConfig() {
        String getuiClient = SPUtils.getInstance(Constant.UE_TOKEN_OTHER_USER_INFO).getString(Constant.SP_GE_TUI_TOKEN, "");
        if (!TextUtils.isEmpty(getuiClient)) {
            OkHttpUtils.getInstance().getStringWithParam(SplashActivity.this, ApiHelper.getConfigUrl(), NETWORK_REQUEST_CONFIG, Params.getConfigPamars());
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("SplashActivity==", "SplashActivity== requestCode = " + requestCode + " response = " + response);
        dissmissDialog();
        switch (requestCode) {
            case NETWORK_REQUEST_CONFIG:
                try {
                    Gson gson = new Gson();
                    ConfigBean configBean = gson.fromJson(response, ConfigBean.class);
                    ConfigBean.DataBean dataBean = configBean.getData();
                    if (configBean.getResult() > 0) {
                        isGetConfig = true;
                        if (!ObjectUtils.isEmpty(dataBean)) {
                            privacyprotocol = dataBean.getPrivacyprotocol();
                            SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.SP_CONFIG_UPDATE_TIME, dataBean.getUpdatetime());
                            JSONObject jsonObject = new JSONObject(response);
                            String data = jsonObject.getString("data");
                            AppConfig.saveAppInfo(data);
                        }
                    } else {
                        if (!isGetConfig) {
                            isGetConfig = true;
                            getConfig();
                        }
//                        ToastUtils.showShort(message);
                        return;
                    }
                } catch (Exception e) {
                    LogUtils.dTag("Exception==", e.toString());
                    //一般为接口错误
                    ToastUtils.showShort(getResources().getString(R.string.str_server_exception));
//                    toMainActivity();
                }
                if (isFirstOpenApp) {
                    showPrivacyDialog();
                } else {
                    doSomething();
                }
                break;
            case NETWORK_REQUEST_SIGN:
                mHandler.removeMessages(3);
                try {
                    signBean = new Gson().fromJson(response, SignBean.class);
                    signResult = signBean.getResult();
                    if (signResult > 0) {
                        //保存用户nodeId
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_ID, String.valueOf(signBean.getData().getNodeid()));
                        //保存用户nodeCode
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_CODE, signBean.getData().getNodecode());
                        //保存用户nodeName
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_NAME, signBean.getData().getNodename());
                        //保存用户手机号
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MOBILE_NO, signBean.getData().getMobileno());
                        //保存用户头像地址
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_HEAD_PHOTO, signBean.getData().getPic());
                        //保存是否有支付密码的状态
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.IS_PAY_PWD, signBean.getData().isIspaypwdnull());
                        //保存最大免密支付金额
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT, String.valueOf(signBean.getData().getMaxnotpwd()));
                        //保存未读消息数量
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NEWMAIL_NUM, String.valueOf(signBean.getData().getNewmailnum()));
                        //保存开通支付密码类型
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NOT_PWD_PAY_TYPE, String.valueOf(signBean.getData().getNotpwdpaytype()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!isGetConfig) {
                    getConfig();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        //网络错误(或者其他错误)
        ToastUtils.showShort(e.getMessage());
        toMainActivity();
    }

    /**
     * 检查app升级
     */
    private void checkAppUpdate() {
        String dataBeanStr = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        ConfigBean.DataBean dataBean = new Gson().fromJson(dataBeanStr, ConfigBean.DataBean.class);
        try {
            //服务器返回的android版本
            String androidversion = new String(EncodeUtils.base64Decode(dataBean.getAndroidversion()));
            //升级地址
            String updateUrl = new String(EncodeUtils.base64Decode(dataBean.getAndroidurl()));
            //升级描述
            String androidcontent = new String(EncodeUtils.base64Decode(dataBean.getAndroidcontent()));
            //获取本地的versionName
            String versionName = AppUtils.getAppVersionName();
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m1 = p.matcher(androidversion);
            Matcher m2 = p.matcher(versionName);
            //网络返回的版本号转为可以比较的整数
            int netVersion = Integer.parseInt(m1.replaceAll("").trim());
            //本地的版本号
            int localVersion = Integer.parseInt(m2.replaceAll("").trim());
            //有升级版本就不展示广告了
            if (netVersion > localVersion) {
                AppUpdate appUpdate = new AppUpdate(SplashActivity.this);
                appUpdate.showUpdateDialog(updateUrl, androidversion, androidcontent, true);
                return;
            }
//        startService(new Intent(this,KeepLifeService.class));

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!isFirstOpenApp) {
            showAdvertising(dataBean);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this); // 基础指标统计，不能遗漏
    }

    /**
     * 展示广告信息
     */
    private void showAdvertising(ConfigBean.DataBean dataBean) {
        String isStartlogo = dataBean.getIsstartlogo();
        if (!ObjectUtils.isEmpty(isStartlogo) && !ObjectUtils.equals("null", isStartlogo)) {
            isStartlogo = new String(EncodeUtils.base64Decode(isStartlogo));
        }
        if (ObjectUtils.equals("1", isStartlogo)) {
            mBottomLogo.setVisibility(View.VISIBLE);
        } else {
            mBottomLogo.setVisibility(View.GONE);
        }
        String advertising = "";
        advertising = new String(EncodeUtils.base64Decode(dataBean.getStartad()));
        try {
            if (!TextUtils.isEmpty(advertising)) {
                List<AdvertisingBean> advertisingBeanList;
                try {
                    advertisingBeanList = new Gson().fromJson(advertising, new TypeToken<List<AdvertisingBean>>() {
                    }.getType());
                } catch (JsonSyntaxException ex) {
                    //只有一张图片的情况
                    if (!advertising.contains(",")) {
                        if (ActivityUtils.isActivityAlive(SplashActivity.this)) {
                            GlideApp.with(this).load(advertising).into(mIvAdvertising);
                        }
                    } else {
                        //多张图片
                        String[] advers = advertising.split(",");
                        //从广告图片中取出一个随机的广告
                        int index = (int) (Math.random() * advers.length);
                        if (ActivityUtils.isActivityAlive(SplashActivity.this)) {
                            GlideApp.with(this).load(advers[index]).into(mIvAdvertising);
                        }
                    }
                    mHandler.sendEmptyMessage(2);
                    return;
                }
                Random random = new Random();
                int n = random.nextInt(advertisingBeanList.size());//取随机数
                AdvertisingBean advertisingBean = advertisingBeanList.get(n);//获取随机广告
//            [{"adIsOn":true,"picUrl":"http://ue.yxhpt.com/pic/ad/ad4.png","secs":3,"adUrl":"http://client.ckv-test.sulink.cn/html/search.aspx?queryName=老狼&pic=http://ghs.ckv-test.sulink.cn/media/1866f223-60be-49ab-95dc-97c2b1351e2e.png&color=white&AppStoreId=81123"}]
                isAdIsOn = advertisingBean.isAdIsOn();
                //只有一张图片的情况
                if (isAdIsOn) {
                    adUrl = advertisingBean.getAdUrl();
                    TIME = advertisingBean.getSecs();
                    String picUrl = advertisingBean.getPicUrl();
                    if (!ObjectUtils.isEmpty(picUrl)) {
                        if (ActivityUtils.isActivityAlive(SplashActivity.this)) {
                            GlideApp.with(this).load(picUrl).into(mIvAdvertising);
                        }
                    }
                }
                mHandler.sendEmptyMessage(2);
            } else {
                toMainActivity();
            }
        } catch (Exception e) {
            toMainActivity();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GetCurrentLocation.destory();
        EventBus.getDefault().unregister(this);
        //销毁当前activity时使用此方法销毁handler,防止内存泄露
        mHandler.removeCallbacksAndMessages(null);
    }


    /**
     * 跳转到主界面
     */
    private void toMainActivity() {
//        if (fromThirdAppLauncher) {
//            //主Activity不在后台则直接正常启动app并保存一个boolean值用来判断是否是第三方应用启动(这个值主要是用来在MainActivity中使用)
//            SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.WHETHER_FROM_THRID_APP, true);
//        }

        if (signResult == -1) {
            //签到接口返回的result=-1时，为冻结状态
            //清除用户配置信息
            if (isLogin) {
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).clear();
                Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                intent.putExtra("flag", "exit");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                ToastUtils.showShort(signBean.getMessage());
                finish();
            } else {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @OnClick({R.id.tv_activity_splash_second, R.id.iv_activity_splash_advertising})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_activity_splash_second:
                toMainActivity();
                break;
            case R.id.iv_activity_splash_advertising:
                if (isAdIsOn) {
                    if (!ObjectUtils.isEmpty(adUrl)) {
                        toWebActivity(adUrl);
                    }
                }
                break;
        }
    }

    /**
     * 跳转WebActivity
     */
    private void toWebActivity(String url) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.TO_WEBVIEW_URL, url);
        intent.putExtra("flag", "advertising");
        startActivity(intent);
        finish();
    }

    public void showLoading() {
        if (qmuiTipDialog != null && qmuiTipDialog.isShowing()) {
            return;
        }
        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord(getString(R.string.str_dialog_loading))
                .create();
        qmuiTipDialog.show();
    }

    public void dissmissDialog() {
        if (qmuiTipDialog != null && qmuiTipDialog.isShowing()) {
            qmuiTipDialog.dismiss();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}
